from get import *
        
def positions(acctids,dtstart,dtend):
    items={}
    getpositions(items,acctids,dtstart,dtend)
    # add information on assets
    uniqueids=set(o['UNIQUEID'][0] for o in items.itervalues()) # get all uniqueids in use
    getassets(items,uniqueids)
    return items.values()

def positionspercents(acctids,dtstart,dtend):
    """Return positions and break down positions according to percentage in each ASSETCLASS.
    Each position object has an additional field ASSETCLASS."""
    positions={}
    getpositions(positions,acctids,dtstart,dtend)
    # add information on assets
    uniqueids=set(o['UNIQUEID'][0] for o in positions.itervalues()) # get all uniqueids in use
    assets={}
    getassetspercents(assets,uniqueids)
    
    newitems=[]
    for key,p in positions.iteritems():
        uniqueid=p['UNIQUEID'][0]
        mktval = p['MKTVAL'][0]
        if mktval<1.: continue
        a = assets[uniqueid]
        if 'percent' in a:
            undefinedmktval=mktval
            for assetclass,percent in a['percent'].iteritems():
                newp = p.copy()
                newp['label']=key+assetclass
                newp['ASSETCLASS']=[assetclass]
                newmktval=mktval*float(percent)/100.
                newp['MKTVAL']=[str(newmktval)]
                if newmktval>1.:
                    newitems.append(newp)
                undefinedmktval-=newmktval
            if undefinedmktval>1.:
                p['MKTVAL'][0]=str(undefinedmktval)
                newitems.append(p)
        elif 'assetClass' in a:
            p['ASSETCLASS']=a['assetClass']
            newitems.append(p)
        else:
            newitems.append(p)
                
    return assets.values()+newitems